<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;

use app\common\logic\Withdraw as CommonWithdraw;

/**
 * 提现接口逻辑
 */
class Withdraw extends ApiBase
{
    
    public static $commonWithdrawLogic = null;
    
    /**
     * 基类初始化
     */
    public function __construct()
    {
        // 执行父类构造方法
        parent::__construct();
        
        empty(static::$commonWithdrawLogic) && static::$commonWithdrawLogic = new CommonWithdraw();
    }
    
    /**
     * 获取收益信息
     */
    public function getEarningsInfo($data = [])
    {
        // JWT解析用户信息
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id']; // 普通用户使用user_id
            
            // 检测并更新VIP状态
            $userLogic = new \app\common\logic\User();
            $userLogic->checkAndUpdateVipStatus($userData['user_id']);
        }
        
        // 调用common层
        $result = static::$commonWithdrawLogic->getEarningsInfo($data);
        
        // 处理common层返回的[状态码, 消息, 数据]格式
        if (is_array($result) && isset($result[0])) {
            if ($result[0] == RESULT_SUCCESS) {
                return isset($result[2]) ? $result[2] : [];
            } else {
                return $this->returnError($result[1] ?? '获取失败');
            }
        }
        
        return $result;
    }
    
    /**
     * 申请提现
     */
    public function applyWithdraw($data = [])
    {
        // JWT解析用户信息
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id']; // 普通用户使用user_id
            
            // 检测并更新VIP状态
            $userLogic = new \app\common\logic\User();
            $userLogic->checkAndUpdateVipStatus($userData['user_id']);
        }
        
        // 调用common层
        $result = static::$commonWithdrawLogic->applyWithdraw($data);
        
        // 处理common层返回的[状态码, 消息, 数据]格式
        if (is_array($result) && isset($result[0])) {
            if ($result[0] == RESULT_SUCCESS) {
                return isset($result[2]) ? $result[2] : '申请成功';
            } else {
                return $this->returnError($result[1] ?? '申请失败');
            }
        }
        
        return $result;
    }
    
    /**
     * 获取提现记录
     * @author 王勇程 <laughskydragon@qq.com>
     * @param array $data
     * @return array
     */
    public function getWithdrawRecords($data = [])
    {
        // 1. JWT解析获取user_id
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }

        // 2. 调用getWhere方法
        $where = static::$commonWithdrawLogic->getWhere($data);

        // 3. 调用common层业务逻辑
        $result = static::$commonWithdrawLogic->getWithdrawRecords($where);

        return $result;
    }
    
    /**
     * 获取提现配置
     */
    public function getWithdrawConfig($data = [])
    {
        // 直接调用common层
        $result = static::$commonWithdrawLogic->getWithdrawConfig();
        
        // 处理common层返回的[状态码, 消息, 数据]格式
        if (is_array($result) && isset($result[0])) {
            if ($result[0] == RESULT_SUCCESS) {
                return isset($result[2]) ? $result[2] : [];
            } else {
                return $this->returnError($result[1] ?? '获取失败');
            }
        }
        
        return $result;
    }
    
    /**
     * 查询提现状态
     */
    public function queryWithdrawStatus($data = [])
    {
        // JWT解析用户信息
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id']; // 普通用户使用user_id
        }
        
        // 调用common层
        $result = static::$commonWithdrawLogic->queryWithdrawStatus($data);
        
        // 处理common层返回的[状态码, 消息, 数据]格式
        if (is_array($result) && isset($result[0])) {
            if ($result[0] == RESULT_SUCCESS) {
                return isset($result[2]) ? $result[2] : [];
            } else {
                return $this->returnError($result[1] ?? '获取失败');
            }
        }
        
        return $result;
    }

    /**
     * 获取提现配置（控制器别名适配：/withdraw/getConfig）
     */
    public function getConfig($data = [])
    {
        $ret = static::$commonWithdrawLogic->getWithdrawConfig();
        return $ret;
    }

    /**
     * 计算提现手续费（控制器别名适配：/withdraw/calculateFee）
     */
    public function calculateFee($data = [])
    {
        $ret = static::$commonWithdrawLogic->calculateWithdrawFee($data);
        return $ret;
    }

    /**
     * 申请提现（控制器别名适配：/withdraw/apply）
     */
    public function apply($data = [])
    {
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }
        $ret = static::$commonWithdrawLogic->applyWithdraw($data);
        return $ret;
    }

    /**
     * 取消提现（控制器别名适配：/withdraw/cancel）
     */
    public function cancel($data = [])
    {
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }
        $ret = static::$commonWithdrawLogic->cancelWithdraw($data);
        return $ret;
    }

    /**
     * 获取提现状态（控制器别名适配：/withdraw/getStatus）
     */
    public function getStatus($data = [])
    {
        $ret = static::$commonWithdrawLogic->queryWithdrawStatus($data);
        return $ret;
    }

    /**
     * 获取提现统计（控制器别名适配：/withdraw/getStats）
     */
    public function getStats($data = [])
    {
        $ret = static::$commonWithdrawLogic->getWithdrawStatistics($data);
        return $ret;
    }

    /**
     * 提现综合页面数据
     * 包含：提现配置与用户余额
     */
    public function getDashboard($data = [])
    {
        // JWT解析用户信息
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            $data['user_id'] = $userData['user_id'];
        }

        $userId = $data['user_id'] ?? 0;

        // 用户余额
        $balance = floatval($this->modelUser->getValue(['id' => $userId], 'available_amount'));

        // 提现配置（使用common层已对用户侧字段做适配）
        $cfgRet = static::$commonWithdrawLogic->getWithdrawConfig();

        return [
            'balance' => number_format($balance, 2),
            'config' => $cfgRet
        ];
    }
}
